<template>
	<view class="container">
		<!-- 第一屏：黄金三秒，锁定眼球 -->
		<view class="section hero">
			<image class="hero-image" src="/static/images/hero-bg.png" mode="widthFix"></image>
			<view class="hero-content">
				<text class="hero-title">AI智能童伴学习机</text>
				<text class="hero-sub">原价 <text class="hero-old">499</text>元，限时补贴价仅需 <text class="hero-price">299元</text>！</text>
				<view class="hero-gift">立即抢购，即赠价值2226元鄂尔多斯全年畅游卡！</view>
				<text class="countdown">限时抢购 | 剩 {{ countdown }}</text>
				<button class="cta-btn" @click="scrollToBuy">立即抢购</button>
			</view>
		</view>
		
		<!-- 第二屏：击中痛点，引发共鸣 -->
		<view class="section">
			<text class="section-title">您是否也有这样的育儿烦恼？</text>
			<view class="pain-points">
				<view class="pain-item" v-for="(point, index) in painPoints" :key="index">
					<image class="pain-icon" :src="point.icon" mode="aspectFit"></image>
					<text class="pain-text">{{ point.text }}</text>
				</view>
			</view>
		</view>
		
		<!-- 第三屏：展示方案，AI智能童伴如何解决一切 -->
		<view class="section">
			<text class="section-title">一台AI智能童伴，就是孩子的全能成长伙伴</text>
			<view class="features">
				<view class="feature" v-for="(feature, index) in features" :key="index">
					<image class="feature-img" :src="feature.gif" mode="aspectFit"></image>
					<view class="feature-content">
						<text class="feature-title">{{ feature.title }}</text>
						<text class="feature-desc">{{ feature.description }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 第四屏：引爆价值，超值赠品详细介绍 -->
		<view class="section">
			<text class="section-title">惊喜不止于此！下单即赠【鄂尔多斯旅游一卡通】</text>
			<image class="gift-card-img" src="/static/images/travel-card.png" mode="widthFix"></image>
			<text class="gift-value">政府补贴，真实价值2226元！</text>
			<text class="gift-desc">全年365天、不限次数、免费畅玩鄂尔多斯数十家核心景区！</text>
			<view class="scenic-list">
				<view class="scenic-item" v-for="(spot, index) in scenicSpots" :key="index">
					<image class="scenic-img" :src="spot.image" mode="aspectFill"></image>
					<text class="scenic-name">{{ spot.name }} <text class="scenic-price">原价{{ spot.price }}元</text></text>
				</view>
			</view>
			<text class="trust-badge">鄂尔多斯文旅局监制</text>
		</view>
		
		<!-- 第五屏：价值对比 -->
		<view class="section">
			<text class="section-title">今天下单，您将获得什么？</text>
			<view class="value-list">
				<view class="value-item" v-for="(item, index) in valueItems" :key="index">
					<text class="value-name">{{ item.name }}</text>
					<text class="value-price">{{ item.price }}</text>
				</view>
			</view>
			<text class="value-total">总价值 2725元</text>
			<text class="value-final">今日特惠价：仅需 299 元！</text>
			<text class="value-save">您立省 2426 元！</text>
		</view>
		
		<!-- 第六屏：信任背书 -->
		<view class="section">
			<view class="testimonials">
				<view class="testimonial" v-for="(testimonial, index) in testimonials" :key="index">
					<image class="testimonial-avatar" :src="testimonial.avatar" mode="aspectFill"></image>
					<text class="testimonial-name">{{ testimonial.name }}</text>
					<text class="testimonial-comment">{{ testimonial.comment }}</text>
				</view>
			</view>
			<view class="certs">
				<view class="cert-item" v-for="(cert, index) in certs" :key="index">
					<image class="cert-icon" :src="cert.icon" mode="aspectFit"></image>
					<text class="cert-text">{{ cert.text }}</text>
				</view>
			</view>
			<view class="promises">
				<view class="promise-item" v-for="(promise, index) in promises" :key="index">
					<image class="promise-icon" :src="promise.icon" mode="aspectFit"></image>
					<text class="promise-text">{{ promise.text }}</text>
				</view>
			</view>
		</view>
		
		<!-- 第七屏：行动号召与购买/分销入口 -->
		<view class="footer">
			<button class="footer-btn" @click="handlePay" :disabled="loading">
				{{ loading ? '处理中...' : '仅299元，立即抢购' }}
			</button>
			<text class="footer-info">成功购买后，您将自动获得分销资格，分享给好友购买，最高可得XX元现金返利！</text>
			<view class="pay-methods">
				<image class="pay-icon" src="/static/images/wechat-pay.png" mode="aspectFit"></image>
				<image class="pay-icon" src="/static/images/alipay.png" mode="aspectFit"></image>
			</view>
		</view>
		
		<!-- 错误提示 -->
		<view v-if="errorMessage" class="error-message">
			{{ errorMessage }}
		</view>
		
		<!-- 支付成功弹窗 -->
		<uni-popup ref="successPopup" type="center">
			<view class="popup">
				<text class="popup-success">支付成功！</text>
				<text class="popup-desc">恭喜您获得分销资格，分享给好友即可赚取佣金！</text>
				<view class="popup-buttons">
					<button class="popup-btn" @click="goToDistribution">去分销中心</button>
					<button class="popup-btn outline" @click="closePopup">继续浏览</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				countdown: '23:59:59',
				showPopup: false,
				isWeixin: false,
				userToken: '',
				loading: false,
				errorMessage: '',
				successMessage: '',
				countdownTimer: null,
				painPoints: [
					{ icon: '/static/images/icon-why.png', text: '孩子总问"为什么"，我却答不上来？' },
					{ icon: '/static/images/icon-busy.png', text: '工作太忙，没时间陪孩子，心怀愧疚？' },
					{ icon: '/static/images/icon-english.png', text: '孩子英语启蒙难，发音不准、不敢说？' },
					{ icon: '/static/images/icon-phone.png', text: '沉迷手机电视，视力下降、不爱交流？' },
					{ icon: '/static/images/icon-homework.png', text: '辅导作业鸡飞狗跳，亲子关系紧张？' }
				],
				features: [
					{ gif: '/static/images/feature-qa.gif', title: '全科知识问答', description: '内置DeepSeek、豆包等顶尖大模型，孩子的"十万个为什么"，它都懂。天文地理、历史人文，张口就问，即刻回答。' },
					{ gif: '/static/images/feature-english.gif', title: '沉浸式英语陪练', description: '标准美式发音，支持实时纠错。从单词到对话，为孩子创造纯正语言环境，自信说出口。' },
					{ gif: '/static/images/feature-writing.gif', title: '高级写作指导', description: '从看图写话到构思作文，AI辅助孩子打开思路，学习修辞手法，提升表达能力。' },
					{ gif: '/static/images/feature-emotion.gif', title: '情绪安抚与聊天', description: '化身贴心"小树洞"，倾听孩子心事，用积极正向的语言进行情绪疏导，培养健康心态。' },
					{ gif: '/static/images/feature-resource.gif', title: '海量学习资源', description: '内置国学经典、成语故事、晚安童话等海量资源，随时随地磨耳朵。' }
				],
				scenicSpots: [
					{ image: '/static/images/spot1.png', name: '响沙湾', price: '280' },
					{ image: '/static/images/spot2.png', name: '成吉思汗陵', price: '180' },
					{ image: '/static/images/spot3.png', name: '鄂尔多斯草原', price: '150' },
					{ image: '/static/images/spot4.png', name: '康巴什新区', price: '120' }
				],
				valueItems: [
					{ name: 'AI智能童伴学习机', price: '市场价 499元' },
					{ name: '鄂尔多斯旅游一卡通', price: '官方价值 2226元' }
				],
				testimonials: [
					{ avatar: '/static/images/avatar1.png', name: '小明妈妈', comment: '太值了！孩子很喜欢这个机器人，旅游卡也真实有效，准备暑假就去鄂尔多斯玩！' },
					{ avatar: '/static/images/avatar2.png', name: '乐乐爸爸', comment: '问什么都能答上来，英语发音比我都标准，解决了我的大难题。' },
					{ avatar: '/static/images/avatar3.png', name: '小美妈妈', comment: '299元买到这么智能的伙伴，还送旅游卡，真的是赚到了！' }
				],
				certs: [
					{ icon: '/static/images/cert-3c.png', text: '3C认证' },
					{ icon: '/static/images/cert-deepseek.png', text: 'DeepSeek技术' },
					{ icon: '/static/images/cert-doubao.png', text: '豆包AI支持' }
				],
				promises: [
					{ icon: '/static/images/icon-auth.png', text: '正品保障' },
					{ icon: '/static/images/icon-return.png', text: '7天无理由' },
					{ icon: '/static/images/icon-warranty.png', text: '一年质保' },
					{ icon: '/static/images/icon-cs.png', text: '在线客服' }
				]
			}
		},
		onLoad() {
			this.checkEnvironment();
			this.loadUserToken();
			this.startCountdown();
			this.ensureWxSDKLoaded();
		},
		methods: {
			checkEnvironment() {
				// #ifdef H5
				this.isWeixin = /micromessenger/i.test(navigator.userAgent);
				// #endif
				// #ifdef MP-WEIXIN
				this.isWeixin = true;
				// #endif
			},
			loadUserToken() {
				// #ifdef H5
				this.userToken = uni.getStorageSync('user_token') || '';
				// #endif
				// #ifdef MP-WEIXIN
				this.userToken = uni.getStorageSync('user_token') || '';
				// #endif
			},
			startCountdown() {
				let end = Date.now() + 24*60*60*1000;
				const update = () => {
					let left = end - Date.now();
					if (left < 0) left = 0;
					let h = String(Math.floor(left/3600000)).padStart(2,'0');
					let m = String(Math.floor(left/60000)%60).padStart(2,'0');
					let s = String(Math.floor(left/1000)%60).padStart(2,'0');
					this.countdown = `${h}:${m}:${s}`;
					if (left > 0) this.countdownTimer = setTimeout(update, 1000);
				};
				update();
			},
			scrollToBuy() {
				uni.pageScrollTo({
					scrollTop: 9999,
					duration: 300
				});
			},
			closePopup() {
				this.$refs.successPopup.close();
			},
			goToDistribution() {
				uni.navigateTo({
					url: '/pages/distribution/center'
				});
			},
			async handlePay() {
				if (!this.isWeixin) {
					uni.showToast({
						title: '请在微信内打开本页面完成支付',
						icon: 'none'
					});
					return;
				}
				
				if (!this.userToken) {
					// 跳转授权
					// #ifdef H5
					let redirect = encodeURIComponent(window.location.href);
					window.location.href = `https://ai.huixinqi.cn/app/aihaowu/user/get_auth_url?redirect=${redirect}`;
					// #endif
					// #ifdef MP-WEIXIN
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					// #endif
					return;
				}
				
				this.loading = true;
				this.errorMessage = '';
				
				try {
					// 创建订单
					const orderRes = await uni.request({
						url: 'https://ai.huixinqi.cn/app/aihaowu/order/create',
						method: 'POST',
						header: { 'Authorization': `Bearer ${this.userToken}` }
					});
					
					if (orderRes.data.code !== 0) {
						this.errorMessage = orderRes.data.msg || '创建订单失败';
						uni.showToast({
							title: this.errorMessage,
							icon: 'none'
						});
						return;
					}
					
					const payParams = orderRes.data.data.pay_params;
					
					// 获取JS-SDK配置
					// #ifdef H5
					let url = window.location.href.split('#')[0];
					// #endif
					// #ifdef MP-WEIXIN
					let url = 'https://ai.huixinqi.cn';
					// #endif
					
					const jsRes = await uni.request({
						url: `https://ai.huixinqi.cn/app/aihaowu/order/js_config?url=${encodeURIComponent(url)}`,
						header: { 'Authorization': `Bearer ${this.userToken}` }
					});
					
					if (jsRes.data.code !== 0) {
						this.errorMessage = jsRes.data.msg || '获取支付配置失败';
						uni.showToast({
							title: this.errorMessage,
							icon: 'none'
						});
						return;
					}
					
					// #ifdef H5
					// H5环境使用微信JS-SDK
					console.log('开始调起微信支付，参数:', payParams);
					
					// 等待JS-SDK加载，设置超时时间
					const waitForWxSDK = () => {
						return new Promise((resolve, reject) => {
							let attempts = 0;
							const maxAttempts = 20; // 最多等待1秒
							
							const check = () => {
								attempts++;
								console.log(`JS-SDK检查第${attempts}次, window.wx:`, window.wx);
								
								if (window.wx && typeof window.wx.config === 'function') {
									console.log('JS-SDK加载成功');
									resolve();
								} else if (attempts >= maxAttempts) {
									console.error('JS-SDK加载超时，尝试直接使用');
									// 超时后尝试直接使用，可能JS-SDK已经加载但检测不到
									if (window.wx) {
										console.log('检测到window.wx存在，尝试直接使用');
										resolve();
									} else {
										reject(new Error('JS-SDK加载超时'));
									}
								} else {
									setTimeout(check, 50);
								}
							};
							check();
						});
					};
					
					try {
						await waitForWxSDK();
						
						console.log('获取到JS-SDK配置:', jsRes.data.data);
						console.log('window.wx:', window.wx);
						console.log('window.wx.config:', window.wx && window.wx.config);
						
						window.wx.config({
							debug: false,
							appId: jsRes.data.data.appId,
							timestamp: jsRes.data.data.timestamp,
							nonceStr: jsRes.data.data.nonceStr,
							signature: jsRes.data.data.signature,
							jsApiList: ['chooseWXPay']
						});
						
						window.wx.ready(() => {
							console.log('wx.ready触发，开始调起支付');
							window.wx.chooseWXPay({
								timestamp: payParams.timeStamp,
								nonceStr: payParams.nonceStr,
								package: payParams.package,
								signType: payParams.signType,
								paySign: payParams.paySign,
								success: (res) => {
									console.log('支付成功:', res);
									this.$refs.successPopup.open();
									uni.showToast({
										title: '支付成功！',
										icon: 'success'
									});
								},
								cancel: (res) => {
									console.log('支付取消:', res);
									uni.showToast({
										title: '支付已取消',
										icon: 'none'
									});
								},
								fail: (res) => {
									console.error('支付失败:', res);
									uni.showToast({
										title: '支付失败：' + (res.errMsg || '未知错误'),
										icon: 'none'
									});
								}
							});
						});
						
						window.wx.error((res) => {
							console.error('wx.error触发:', res);
							uni.showToast({
								title: '微信支付配置失败',
								icon: 'none'
							});
						});
						
					} catch (error) {
						console.error('JS-SDK加载失败:', error);
						uni.showToast({
							title: '微信JS-SDK加载失败，请刷新页面重试',
							icon: 'none'
						});
					}
					// #endif
					
					// #ifdef MP-WEIXIN
					// 小程序环境使用uni.requestPayment
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payParams.timeStamp,
						nonceStr: payParams.nonceStr,
						package: payParams.package,
						signType: payParams.signType,
						paySign: payParams.paySign,
						success: (res) => {
							this.$refs.successPopup.open();
							uni.showToast({
								title: '支付成功！',
								icon: 'success'
							});
						},
						fail: (res) => {
							uni.showToast({
								title: '支付失败：' + (res.errMsg || '未知错误'),
								icon: 'none'
							});
						}
					});
					// #endif
					
				} catch (error) {
					this.errorMessage = '网络错误，请重试';
					uni.showToast({
						title: this.errorMessage,
						icon: 'none'
					});
					console.error('支付错误:', error);
				} finally {
					this.loading = false;
				}
			},
			ensureWxSDKLoaded() {
				// #ifdef H5
				// 检查JS-SDK是否已经加载
				if (!window.wx || typeof window.wx.config !== 'function') {
					console.log('JS-SDK未加载，尝试动态加载...');
					
					// 动态加载JS-SDK
					const script = document.createElement('script');
					script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
					script.onload = () => {
						console.log('JS-SDK动态加载成功');
						uni.showToast({
							title: 'JS-SDK加载成功',
							icon: 'success'
						});
					};
					script.onerror = () => {
						console.error('JS-SDK动态加载失败');
						uni.showToast({
							title: 'JS-SDK加载失败，请检查网络',
							icon: 'none'
						});
					};
					document.head.appendChild(script);
				} else {
					console.log('JS-SDK已加载');
				}
				// #endif
			}
		},
		onUnload() {
			if (this.countdownTimer) {
				clearTimeout(this.countdownTimer);
			}
		}
	}
</script>

<style scoped>
.container { background: #f8f8f8; min-height: 100vh; }
.section { padding: 24px 16px; background: #fff; margin-bottom: 12px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); }
.hero { text-align: center; position: relative; }
.hero-image { width: 100%; border-radius: 16px; }
.hero-content { padding: 16px 0; }
.hero-title { font-size: 2em; font-weight: bold; margin: 16px 0 8px; display: block; }
.hero-sub { color: #e53935; font-size: 1.2em; margin-bottom: 8px; display: block; }
.hero-price { font-size: 1.5em; color: #ff9800; font-weight: bold; }
.hero-old { text-decoration: line-through; color: #aaa; margin-left: 8px; }
.hero-gift { background: linear-gradient(90deg,#ff9a44,#ff5f6d); color: #fff; border-radius: 24px; padding: 8px 20px; display: inline-block; margin: 12px 0; font-size: 1.1em; }
.countdown { font-size: 1.2em; color: #e53935; margin: 12px 0; display: block; }
.cta-btn { background: linear-gradient(90deg,#ff9a44,#ff5f6d); color: #fff; border: none; border-radius: 32px; font-size: 1.2em; padding: 16px 0; width: 90%; margin: 20px auto 0; display: block; font-weight: bold; box-shadow: 0 4px 12px rgba(255,105,135,0.15); }
.section-title { font-weight: bold; font-size: 1.2em; margin-bottom: 12px; display: block; }
.pain-points { display: flex; flex-wrap: wrap; gap: 16px; justify-content: space-around; }
.pain-item { width: 45%; background: #f5f5f5; border-radius: 12px; padding: 16px; text-align: center; margin-bottom: 8px; }
.pain-icon { width: 48px; height: 48px; margin-bottom: 8px; }
.pain-text { font-size: 0.9em; }
.features { display: flex; flex-direction: column; gap: 20px; }
.feature { display: flex; gap: 16px; align-items: center; background: #f9f9f9; border-radius: 12px; padding: 12px; }
.feature-img { width: 72px; height: 72px; border-radius: 12px; }
.feature-content { flex: 1; }
.feature-title { font-weight: bold; font-size: 1.1em; margin-bottom: 4px; display: block; }
.feature-desc { font-size: 0.9em; color: #666; }
.gift-card-img { width: 100%; border-radius: 12px; margin-bottom: 12px; }
.gift-value { color: #e53935; font-size: 1.3em; font-weight: bold; margin-bottom: 8px; display: block; }
.gift-desc { margin-bottom: 8px; display: block; }
.scenic-list { display: flex; flex-wrap: wrap; gap: 8px; }
.scenic-item { width: 48%; background: #f5f5f5; border-radius: 10px; margin-bottom: 8px; padding: 8px; text-align: center; }
.scenic-img { width: 100%; border-radius: 8px; height: 80px; }
.scenic-name { font-size: 0.9em; }
.scenic-price { color: #888; }
.trust-badge { margin-top: 8px; color: #4caf50; font-weight: bold; display: block; }
.value-list { margin: 16px 0; }
.value-item { display: flex; justify-content: space-between; margin-bottom: 8px; }
.value-name { flex: 1; }
.value-price { text-align: right; }
.value-total { text-align: right; font-size: 1.1em; color: #888; text-decoration: line-through; display: block; }
.value-final { text-align: right; font-size: 1.5em; color: #e53935; font-weight: bold; display: block; }
.value-save { text-align: right; color: #4caf50; font-size: 1.1em; display: block; }
.testimonials { display: flex; overflow-x: auto; gap: 12px; margin-bottom: 12px; }
.testimonial { min-width: 180px; background: #f5f5f5; border-radius: 10px; padding: 12px; text-align: center; }
.testimonial-avatar { width: 48px; height: 48px; border-radius: 50%; margin-bottom: 6px; }
.testimonial-name { font-weight: bold; display: block; }
.testimonial-comment { font-size: 0.9em; color: #666; }
.certs, .promises { display: flex; gap: 12px; justify-content: center; margin-bottom: 8px; flex-wrap: wrap; }
.cert-item, .promise-item { background: #f5f5f5; border-radius: 8px; padding: 8px 12px; font-size: 0.95em; display: flex; align-items: center; gap: 6px; }
.cert-icon, .promise-icon { width: 24px; height: 24px; }
.cert-text, .promise-text { font-size: 0.9em; }
.footer { position: fixed; left: 0; right: 0; bottom: 0; background: #fff; box-shadow: 0 -2px 8px rgba(0,0,0,0.06); padding: 16px 0 8px; z-index: 100; }
.footer-btn { width: 90%; margin: 0 auto; display: block; background: linear-gradient(90deg,#ff9a44,#ff5f6d); color: #fff; border: none; border-radius: 32px; font-size: 1.2em; padding: 16px 0; font-weight: bold; }
.footer-btn[disabled] { opacity: 0.6; }
.footer-info { text-align: center; color: #888; font-size: 0.95em; margin-top: 8px; display: block; }
.pay-methods { display: flex; justify-content: center; gap: 16px; margin-top: 8px; }
.pay-icon { width: 48px; height: 32px; }
.error-message { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #f44336; color: #fff; padding: 12px 20px; border-radius: 8px; z-index: 1000; font-size: 0.9em; }
.popup { background: #fff; border-radius: 16px; padding: 32px 24px; text-align: center; }
.popup-success { color: #4caf50; font-size: 1.3em; margin-bottom: 12px; display: block; }
.popup-desc { margin-bottom: 16px; display: block; }
.popup-buttons { display: flex; gap: 12px; justify-content: center; }
.popup-btn { background: #ff9a44; color: #fff; border: none; border-radius: 24px; padding: 12px 32px; font-size: 1.1em; }
.popup-btn.outline { background: #eee; color: #333; }
</style> 